package com.lucher.mes.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lucher.mes.common.Tools;
import com.lucher.mes.dao.MaterialdepotMapper;
import com.lucher.mes.dao.MaterialinoutMapper;
import com.lucher.mes.dao.OperatorMapper;
import com.lucher.mes.dao.ProduceinfoMapper;
import com.lucher.mes.dao.ProducematerialMapper;
import com.lucher.mes.dao.ProduceproductMapper;
import com.lucher.mes.dao.ProductMapper;
import com.lucher.mes.po.Materialdepot;
import com.lucher.mes.po.Materialinout;
import com.lucher.mes.po.Operator;
import com.lucher.mes.po.Produceinfo;
import com.lucher.mes.po.Producematerial;
import com.lucher.mes.po.Produceproduct;
import com.lucher.mes.po.Product;
import com.lucher.mes.po.Toolplateinfo;
import com.lucher.mes.service.IProductdepotService;

@Controller
@RequestMapping("/producematerial")  
public class ProducematerialController extends BaseController{
	@Autowired
	private ProducematerialMapper producematerialDao;
	@Autowired
	private MaterialdepotMapper materialdepotDao;
	@Autowired
	private OperatorMapper operatorDao;
	@Autowired
	private MaterialinoutMapper materialinoutDao;
	@Autowired
	private ProduceinfoMapper produceinfoDao;
	@Autowired
	private IProductdepotService productdepotService;
	@Autowired
	private ProduceproductMapper produceproductDao;
	
	
	
	/*
     * 特殊的instance变量
     * 注：零长度的byte数组对象创建起来将比任何对象都经济――查看编译后的字节码：
     * 生成零长度的byte[]对象只需3条操作码，而Object lock = new Object()则需要7行操作码。
     */
    private static byte[] lock = new byte[0];
	
	/**
	 * 查询信息
	 */
	@RequestMapping(value = "/findByList")
	public String findByList(Producematerial form) {
		return "producematerial/findProducematerialList";
	}
	
	/**
	 * 查询信息Json
	 */
	@ResponseBody
	@RequestMapping(value = "/findListJson")
	public Map<String, Object> findListJson(Producematerial form) {
		//封装JSon的Map
		Map<String, Object> result = new HashMap<String, Object>(); 
		result.put("code", "0");
		List<HashMap<String, Object>> objectlist = new ArrayList<HashMap<String, Object>>();
		
		Integer total = producematerialDao.findByCount(form);
		List<Producematerial> list = producematerialDao.findByListForPage(form);
		
		for (Producematerial producematerial : list) {
			HashMap<String, Object> objectMap = new HashMap<String, Object>();
			
			objectMap.put("id", producematerial.getId());
			objectMap.put("producecode", producematerial.getProducecode());
			objectMap.put("productcode", producematerial.getProductcode());
			objectMap.put("productname", producematerial.getProductname());
			objectMap.put("batchno", producematerial.getBatchno());
			objectMap.put("materialcode", producematerial.getMaterialcode());
			objectMap.put("materialname", producematerial.getMaterialname());
			objectMap.put("amount", producematerial.getAmount());
			objectMap.put("peramount", producematerial.getPeramount());
			objectMap.put("outamount", producematerial.getOutamount());
			objectMap.put("status", producematerial.getStatus());
			objectMap.put("remark", producematerial.getRemark());
			
			objectlist.add(objectMap);
		}
		
		result.put("count", total);
		result.put("data", objectlist);
		return result;
	}

	/**
	 * 添加信息初始化
	 * 
	 * @return
	 */
	@RequestMapping(value = "/addInit")
	public String addInit(Producematerial form) {
		return "producematerial/addProducematerial";
	}

	/**
	 * 新增
	 */
	@ResponseBody //此标志就是返回jesion数据给页面的标志
	@RequestMapping(value = "/save")
	public Map<String,Object>  save(Producematerial form) {
		
		//封装返回给页面的json对象
		HashMap<String,Object> responseJson = new HashMap<String,Object>();
		responseJson.put("code", "0");
		
		if ("".equals(form.getProducecode())) {
			responseJson.put("flag", "0"); //操作失败
			responseJson.put("msg", "操作失败，请输入产品编码");
			return responseJson;
		} 
		
		//保存信息
		Integer producematerialId = producematerialDao.insertSelective(form);
		
		responseJson.put("flag", "1");//操作成功
		responseJson.put("msg", "操作成功");
		
		return responseJson;
	}

	/**
	 * 更新初始化
	 */
	@RequestMapping(value = "/updateInit")
	public String updateInit(Producematerial form) {
		Producematerial producematerial = producematerialDao.selectByPrimaryKey(form.getId());
		form.setProducematerial(producematerial);

		return "producematerial/updateProducematerial";
	}

	/**
	 * 更新
	 */
	@ResponseBody //此标志就是返回jesion数据给页面的标志
	@RequestMapping(value = "/update")
	public Map<String,Object> update(Producematerial form) {
		//封装返回给页面的json对象
		HashMap<String,Object> responseJson = new HashMap<String,Object>();
		responseJson.put("code", "0");
		
		if ("".equals(form.getProductcode())) {
			responseJson.put("flag", "0"); //添加失败
			responseJson.put("msg", "操作失败，产品编码不能为空");
			return responseJson;
		}
		
		// 修改信息
		int flag = producematerialDao.updateByPrimaryKeySelective(form);
		
		responseJson.put("flag", "1");//
		responseJson.put("msg", "操作成功");
		return responseJson;
	}
    
	/**
	 * 删除
	 * @return
	 */
	@ResponseBody //此标志就是返回jesion数据给页面的标志
	@RequestMapping(value="/delete")
	public Map<String,Object> delete(Producematerial form) {
		//封装返回给页面的json对象
		HashMap<String,Object> responseJson = new HashMap<String,Object>();
		responseJson.put("code", "0");
		//删除材料
		producematerialDao.deleteByPrimaryKey(form.getId());
		
		responseJson.put("flag", "1");//删除成功
		responseJson.put("msg", "操作成功");
		
		return responseJson;
	}
	
	/**
	 * 批量删除
	 * @return
	 */
	@ResponseBody //此标志就是返回jesion数据给页面的标志
	@RequestMapping(value="/deleteBatch")
	public Map<String,Object> deleteBatch(@RequestBody List<Producematerial> formlist) {
		//封装返回给页面的json对象
		HashMap<String,Object> responseJson = new HashMap<String,Object>();
		responseJson.put("code", "0");
		for (Producematerial producematerial : formlist) {
			//删除材料
			producematerialDao.deleteByPrimaryKey(producematerial.getId());
		}

		responseJson.put("flag", "1");//删除成功
		responseJson.put("msg", "操作成功");
		
		return responseJson;
	}
	
	/**
	 * 生产任务材料出库
	 */
	@RequestMapping(value = "/outdepotInit")
	public String outdepotInit(Produceinfo form,Model model) {
		Produceinfo produceinfo = produceinfoDao.selectByPrimaryKey(form.getId());
		form.setProduceinfo(produceinfo);
		//model.addAttribute("materialdepotlist", materialdepotDao.findByList(materialdepot));
		model.addAttribute("operatorlist", operatorDao.findOperatorList(new Operator()));
		return "producematerial/outdepot";
	}
	
	/**
	 * 保存生产材料出库
	 */
	@RequestMapping(value = "/saveOutdepot")
	@ResponseBody //此标志就是返回jesion数据给页面的标志
	public  Map<String,Object>  saveOutdepot(Produceinfo record, Produceproduct form) {
		Operator operator = (Operator)getSession().getAttribute("Operator");
		
		//封装返回给页面的json对象
		HashMap<String,Object> responseJson = new HashMap<String,Object>();
		responseJson.put("code", "0");
		
		//加锁
		synchronized(lock) {
			Produceinfo produceinfo = produceinfoDao.selectByPrimaryKey(record.getId());
			
			if(produceinfo == null){
				responseJson.put("flag", "0"); //操作失败
				responseJson.put("msg", "操作失败，此生产任务不存在");
				return responseJson;
			}
			//已经出库量
			int outamount = produceinfo.getOutamount();
			
			if("已完成".equals(produceinfo.getOutstatus())){
				responseJson.put("flag", "0"); //操作失败
				responseJson.put("msg", "操作失败，此生产任务已经完成全部材料出库");
				return responseJson;
			}
			
		    if(produceinfo.getAmount()-outamount < form.getDepotamount()*form.getPackamount()){
		    	responseJson.put("flag", "0"); //操作失败
				responseJson.put("msg", "操作失败，本次出库数量不能大于生产任务剩余总数");
				return responseJson;
		    }
			
		    //查询该生产任务需要的材料信息列表
		    Producematerial producematerialDemo = new Producematerial();
		    producematerialDemo.setProducecode(produceinfo.getProducecode());
		    List<Producematerial> producematerialList =  producematerialDao.findByList(producematerialDemo);
		    
		    for (Producematerial producematerial : producematerialList) {
		    	//查询库存中物料信息
				Materialdepot mateiraldepot = materialdepotDao.findByMaterialcode(producematerial.getMaterialcode());
				if(mateiraldepot == null){
					responseJson.put("flag", "0"); //操作失败
					responseJson.put("msg", "操作失败，库存中不存在此材料 "+producematerial.getMaterialname());
					return responseJson;
				}
				
				if(mateiraldepot.getDepotamount() < producematerial.getPeramount() * form.getDepotamount()*form.getPackamount()){
					responseJson.put("flag", "0"); //操作失败
					responseJson.put("msg", "操作失败，"+producematerial.getMaterialname()+" 的库存量不够本次出库数量");
					return responseJson;
				}
			}
		    
		    //修改生产线信息
		    produceinfo.setOutamount(produceinfo.getOutamount() + form.getDepotamount()*form.getPackamount());
		    if(produceinfo.getOutamount() == produceinfo.getAmount()){ //全部出库
		    	produceinfo.setOutstatus("已完成");
		    }
		    produceinfoDao.updateByPrimaryKeySelective(produceinfo);
		    
		    //添加生产任务产品信息
		    //获取产品批次号
		    //String currenttime = Tools.getCurrentTime();
		    form.setProductstatus("待生产");
			form.setPrintflag("未打印");
			//form.setAddtime(currenttime);//页面已经输入出库时间
			form.setId(null);
			form.setProductcode(produceinfo.getProductcode());
			form.setProductname(produceinfo.getProductname());
			
			//封装材料出入库。方便批量插入
			ArrayList<Materialinout> materialinoutlist = new ArrayList<Materialinout>();
			
		    for (int i = 1; i <= form.getPackamount(); i++) {
		    	String batchno = productdepotService.getProductbatchno(produceinfo.getProductcode());
				form.setBatchno(batchno);
				form.setId(null);
				form.setOldbatchno(null);//新建的产品没有旧产品编号
				form.setChecktimes(1);//默认都是第一次质检
				
				produceproductDao.insertSelective(form);
				
				for (Producematerial producematerial : producematerialList) {
					
					//更新订单材料出库数
					producematerial.setOutamount(producematerial.getOutamount()+producematerial.getPeramount() * form.getDepotamount());
					if(producematerial.getOutamount() == producematerial.getAmount()){
						producematerial.setStatus("已完成");
					}
					producematerialDao.updateByPrimaryKeySelective(producematerial);
					
			    	//查询库存中物料信息
					Materialdepot mateiraldepot = materialdepotDao.findByMaterialcode(producematerial.getMaterialcode());
					//已有库存量
					int depotamount = mateiraldepot.getDepotamount();
					//本次出库量
					int inoutamount = producematerial.getPeramount() * form.getDepotamount();
					mateiraldepot.setDepotamount(depotamount-inoutamount);
					if(depotamount-inoutamount == 0){
						mateiraldepot.setDepotstatus("无库存"); //无库存
					}
					materialdepotDao.updateByPrimaryKeySelective(mateiraldepot);
					
					//增加产品材料出库记录
					Materialinout materialinout = new Materialinout();
					materialinout.setMaterialcode(producematerial.getMaterialcode());
					materialinout.setMaterialname(producematerial.getMaterialname());
					materialinout.setOperatorcode(operator.getLoginname());
					materialinout.setBatchno(batchno);
					materialinout.setType("出库");
					materialinout.setInoutamount(inoutamount);
					materialinout.setAddtime(form.getAddtime());//页面传入出库时间
					materialinout.setInoutercode(operator.getLoginname());
					materialinout.setInoutstatus("已领");
					materialinout.setDepotrackcode(mateiraldepot.getDepotrackcode());
					materialinout.setProducecode(produceinfo.getProducecode());
					materialinoutlist.add(materialinout);
					//materialinoutDao.insertSelective(materialinout);
				}
			}
		    
		    //批量保存材料
		    if(materialinoutlist != null && materialinoutlist.size() > 0){
		    	materialinoutDao.saveBatch(materialinoutlist);
		    }
		    
		    responseJson.put("flag", "1"); 
			responseJson.put("msg", "操作成功");
			return responseJson;
		}
	}
}
